import store from '@/store'
import { Toast } from 'vant'
import { createRouter, createWebHashHistory } from 'vue-router'
import Home from '../views/Home.vue'

const routes = [
  {
    path: '/',
    name: 'home',
    component: Home
  },
  {
    path: '/detail/:id',
    name: 'detail',
    // route level code-splitting
    // this generates a separate chunk (about.[hash].js) for this route
    // which is lazy-loaded when the route is visited.
    component: () => import(/* webpackChunkName: "detail" */ '../views/Detail.vue')
  },
  {
    path: '/login',
    name: 'login',
    component: () => import(/* webpackChunkName: "detail" */ '../views/Login.vue')
  },
  {
    path: '/person',
    name: 'person',
    component: () => import(/* webpackChunkName: "person" */ '../views/Person.vue')
  },
  {
    path: '/store',
    name: 'store',
    component: () => import(/* webpackChunkName: "store" */ '../views/Store.vue')
  },
  {
    path: '/update',
    name: 'update',
    component: () => import(/* webpackChunkName: "update" */ '../views/Update.vue')
  },
  {
    path:"/:pathMatch(.*)*",
    redirect:"/"
  }
]

const router = createRouter({
  history: createWebHashHistory(),
  routes
})
  // 路由的全局守卫
  router.beforeEach(async(to,from,next)=>{
    // 下面的三个路由没有登录，不能访问
    let unsafe = ["/person","/update","/store"]
    if(unsafe.includes(to.path)){
      // 需要登录后，才能进入
      let {isLogin} = store.state
      if(isLogin == null){
        isLogin = await store.dispatch("changeIsLoginAsync")
      }
      if(!isLogin){
        Toast.fail("请先登录")
        // 带to参数的目的事
        // 去/persion  没有登录 拦截到了  登录  登录成功后跳转
        // 去/update  没有登录 拦截到了  登录  登录成功后跳转
        // 去/store  没有登录 拦截到了  登录  登录成功后跳转
        // 之前 ：登录成功后，去哪里了答：个人中心
        // 现在：根据to参数，登录成功后，去合适的地方
        next(`/login?to=${to.path}`)
        return
      }
    }
    next()
  })

export default router
